package com.syezon.wifikey.ad;

import android.app.Activity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.Glide;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.hodanet.appadvplatclient.ReportAgent;
import com.hodanet.appadvplatclient.ad.AdInfo;
import com.qq.e.ads.nativ.NativeADEventListener;
import com.qq.e.ads.nativ.NativeADUnifiedListener;
import com.qq.e.ads.nativ.NativeUnifiedAD;
import com.qq.e.ads.nativ.NativeUnifiedADData;
import com.qq.e.comm.constants.AdPatternType;
import com.qq.e.comm.util.AdError;
import com.syezon.wifikey.R;
import com.syezon.wifikey.channel.ChannelConfig;
import com.syezon.wifikey.config.GDTConfig;
import com.syezon.wifikey.config.TTAdManagerHolder;
import com.syezon.wifikey.imageloader.ImageLoader;
import com.syezon.wifikey.splash.config.SplashConfig;


import java.util.ArrayList;
import java.util.List;

public class NewBannerAd {
    private TTNativeExpressAd mTTNativateExpressAd;
    private ViewGroup viewGroup;
    private Activity activity;
    private CommonAdCallBack commonAdCallBack;
    private CommonNewAdCallBack commonNewAdCallBack;
    private CommonAdConfig bannerAdConfig;
    private int retryCount = 0;
    private String cjsCode;
    private String gdtCode;
    private OnSelfBannerClickListener onSelfBannerClickListener;

    public void setOnSelfBannerClickListener(OnSelfBannerClickListener onSelfBannerClickListener) {
        this.onSelfBannerClickListener = onSelfBannerClickListener;
    }

    public CommonAdConfig getBannerAdConfig() {
        return bannerAdConfig;
    }

    public interface OnSelfBannerClickListener {
        void onSelfBannerClick(AdInfo adInfo);
    }

    public void setCommonNewAdCallBack(CommonNewAdCallBack commonNewAdCallBack) {
        this.commonNewAdCallBack = commonNewAdCallBack;
    }

    public void setCommonAdCallBack(CommonAdCallBack commonAdCallBack) {
        this.commonAdCallBack = commonAdCallBack;
    }

    public NewBannerAd(Activity activity, ViewGroup viewGroup) {
        this.viewGroup = viewGroup;
        this.activity = activity;
    }

    public NewBannerAd(Activity activity, ViewGroup viewGroup, String configCode, String csjCode, String gdtCode) {
        this.cjsCode = csjCode;
        this.gdtCode = gdtCode;
        this.viewGroup = viewGroup;
        this.activity = activity;
        bannerAdConfig = new CommonAdConfig(CommonAdViewModel.KEY_PREFIX + configCode);
    }

    public void loadBannerAdByAdInfo() {
        if (bannerAdConfig == null) {
            throw new RuntimeException(" must implement SplashOldCallBack");
        }

        AdInfo nextAdSource = bannerAdConfig.getNextAdSource();
        loadBannerAdByAdInfo(nextAdSource);
    }

    private void onLoadFail(String code, String errorMsg) {
        if(bannerAdConfig == null) {
            return;
        }
        bannerAdConfig.saveLastShowLocalAdCode(code);
        String localAdSource = bannerAdConfig.getLocalAdSource();
        loadBannerAdByAdInfo(localAdSource);
    }

    private void onLoadFail(AdInfo adInfo, String errorMsg) {
        if (bannerAdConfig == null) {
            return;
        }
        bannerAdConfig.saveLastShowLocalAdCode(adInfo);
        bannerAdConfig.saveLastShowAd(adInfo);

        if (bannerAdConfig.getAdList().size() == 1) {
            String localAdSource = bannerAdConfig.getLocalAdSource();
            if (SplashConfig.SPLASH_AD_SOURCE_GDT.equals(localAdSource)) {
                loadGdtBannerAd(gdtCode);
            } else if (SplashConfig.SPLASH_AD_SOURCE_TT.equals(localAdSource)) {
                loadCsjBannerAd(cjsCode);
            }
        } else {
            retryCount++;

            if (bannerAdConfig.getAdList().size() == retryCount) {
                return;
            }

            AdInfo nextAdSource = bannerAdConfig.getNextAdSource();
            loadBannerAdByAdInfo(nextAdSource);
        }
    }

    public void loadBannerAdByAdInfo(AdInfo adInfo) {
        if (adInfo == null) {
            return;
        }

        if (adInfo.getType() == AdInfo.AD_TYPE_CHUAN_SHAN_JIA) {
            loadCsjBannerAd(adInfo);
        } else if (adInfo.getType() == AdInfo.AD_TYPE_GUANG_DIAN_TONG) {
            loadGdtBannerAd(adInfo);
        } else {
            loadSelfBannerAd(adInfo);
        }
    }

    private void loadSelfBannerAd(AdInfo adInfo) {
        try {
            viewGroup.setVisibility(View.VISIBLE);
            viewGroup.removeAllViews();
            ImageView imageView = new ImageView(activity);
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.gravity = Gravity.BOTTOM;
            imageView.setLayoutParams(layoutParams);
            imageView.setOnClickListener(view -> {
                if (onSelfBannerClickListener != null) {
                    onSelfBannerClickListener.onSelfBannerClick(adInfo);
                }else {
                    AdUtils.adClicked(activity,adInfo);
                }
            });

            if (activity != null && !activity.isDestroyed()) {
                try {
                    Glide.with(activity)
                            .load(adInfo.getPic())
                            .into(imageView);
                } catch (Exception ignored) {

                }
            }

            ReportAgent.reportAdvExtShow(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
            viewGroup.addView(imageView);
            if (commonNewAdCallBack != null) {
                commonNewAdCallBack.onLoadSuccess(adInfo);
            } else {
                onLoadSuccess(adInfo);
            }
        } catch (Exception ignored) {

        }
    }

    private void loadBannerAdByAdInfo(String code) {
        if (TextUtils.isEmpty(code)) {
            return;
        }

        if (SplashConfig.SPLASH_AD_SOURCE_GDT.equals(code)) {
            loadGdtBannerAd(code);
        } else if (SplashConfig.SPLASH_AD_SOURCE_TT.equals(code)) {
            loadCsjBannerAd(code);
        }
    }

    private void loadCsjBannerAd(final String code) {
        try {
            //设置广告参数
            AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(code) //广告位id
                    .setSupportDeepLink(true)
                    .setExpressViewAcceptedSize(340, 0) //期望模板广告view的size,单位dp
                    .setImageAcceptedSize(640, 320)//这个参数设置即可，不影响模板广告的size
                    .build();
            //加载广告
            TTAdManagerHolder.get().createAdNative(Utils.getApp()).loadBannerExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
                @Override
                public void onError(int i, String s) {
                    LogUtils.e("CSJ onError " + s);
                    viewGroup.removeAllViews();
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, code, SDKReportHelper.OP_TYPE_FAIL);
                    if (commonAdCallBack != null) {
                        commonAdCallBack.onLoadFail(code, s);
                    } else {
                        onLoadFail(code, s);
                    }
                }

                @Override
                public void onNativeExpressAdLoad(List<TTNativeExpressAd> list) {
                    if (list == null || list.isEmpty()) {
                        return;
                    }
                    TTNativeExpressAd ttNativeExpressAd = list.get(0);
                    if (ttNativeExpressAd == null) {
                        return;
                    }
                    mTTNativateExpressAd = ttNativeExpressAd;
                    mTTNativateExpressAd.render();
                    bindCSJAdListener(mTTNativateExpressAd, code);
                }
            });

        } catch (Exception ignored) {

        }
    }

    private void loadCsjBannerAd(final AdInfo adInfo) {
        try {
            //设置广告参数
            AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(adInfo.getCode()) //广告位id
                    .setSupportDeepLink(true)
                    .setExpressViewAcceptedSize(340, 0) //期望模板广告view的size,单位dp
                    .setImageAcceptedSize(640, 320)//这个参数设置即可，不影响模板广告的size
                    .build();
            //加载广告
            TTAdManagerHolder.get().createAdNative(Utils.getApp()).loadBannerExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
                @Override
                public void onError(int i, String s) {
                    LogUtils.e("CSJ onError " + s);
                    viewGroup.removeAllViews();
                    ReportAgent.reportAdvSdkFailed(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                    if (commonNewAdCallBack != null) {
                        commonNewAdCallBack.onLoadFail(adInfo, s);
                    } else {
                        onLoadFail(adInfo, s);
                    }
                }

                @Override
                public void onNativeExpressAdLoad(List<TTNativeExpressAd> list) {
                    LogUtils.e("CSJ onNativeExpressAdLoad " + list);
                    if (list == null || list.isEmpty()) {
                        LogUtils.e("CSJ onNativeExpressAdLoad       list.isEmpty()");
                        return;
                    }
                    TTNativeExpressAd ttNativeExpressAd = list.get(0);
                    if (ttNativeExpressAd == null) {
                        LogUtils.e("CSJ onNativeExpressAdLoad       ttNativeExpressAd == null");
                        return;
                    }
                    mTTNativateExpressAd = ttNativeExpressAd;
                    mTTNativateExpressAd.render();
                    bindCSJAdListener(mTTNativateExpressAd, adInfo);
                }
            });

        } catch (Exception e) {

        }
    }

    public static void updateAdAction(Button button, NativeUnifiedADData ad) {
        if (!ad.isAppAd()) {
            button.setText("浏览");
            return;
        }
        switch (ad.getAppStatus()) {
            case 0:
                button.setText("下载");
                break;
            case 1:
                button.setText("启动");
                break;
            case 2:
                button.setText("更新");
                break;
            case 4:
                button.setText(ad.getProgress() + "%");
                break;
            case 8:
                button.setText("安装");
                break;
            case 16:
                button.setText("重新下载");
                break;
            default:
                button.setText("浏览");
                break;
        }
    }

    public void onLoadSuccess(AdInfo adSourceAd) {
        retryCount = 0;
        if(bannerAdConfig == null) {
            return;
        }
        bannerAdConfig.saveLastShowAd(adSourceAd);
        bannerAdConfig.saveLastShowLocalAdCode(adSourceAd);
    }


    //绑定广告行为
    private void bindCSJAdListener(TTNativeExpressAd ad, final String code) {
        ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
            boolean reportShow;

            @Override
            public void onAdClicked(View view, int type) {
                LogUtils.e("CSJ onAdClicked ");
                SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, code, SDKReportHelper.OP_TYPE_CLICK);
            }

            @Override
            public void onAdShow(View view, int type) {
                if (commonAdCallBack != null) {
                    commonAdCallBack.onLoadSuccess(code);
                }
                LogUtils.e("CSJ onAdShow ");
                if (!reportShow) {
                    reportShow = true;
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, code, SDKReportHelper.OP_TYPE_SHOW);
                }
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
                LogUtils.e("CSJ onRenderFail ");
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
                //在渲染成功回调时展示广告，提升体验
                LogUtils.e("CSJ onRenderSuccess ");
                viewGroup.setVisibility(View.VISIBLE);
                viewGroup.removeAllViews();
                viewGroup.addView(view);
            }
        });
        ad.setDownloadListener(new TTAppDownloadListener() {

            boolean reportDownload;
            boolean reportInstall;

            @Override
            public void onIdle() {

            }

            @Override
            public void onDownloadActive(long l, long l1, String s, String s1) {

            }

            @Override
            public void onDownloadPaused(long l, long l1, String s, String s1) {

            }

            @Override
            public void onDownloadFailed(long l, long l1, String s, String s1) {

            }

            @Override
            public void onDownloadFinished(long l, String s, String s1) {
                if (!reportDownload) {
                    reportDownload = true;
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, code, SDKReportHelper.OP_TYPE_DOWNLOAD);
                }
            }

            @Override
            public void onInstalled(String s, String s1) {
                if (!reportInstall) {
                    reportInstall = true;
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_CSJ, code, SDKReportHelper.OP_TYPE_INSTALL);
                }
            }
        });
    }


    //绑定广告行为
    private void bindCSJAdListener(final TTNativeExpressAd ad, final AdInfo adInfo) {
        ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
            boolean reportShow;

            @Override
            public void onAdClicked(View view, int type) {
                ReportAgent.reportAdvClick(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
            }

            @Override
            public void onAdShow(View view, int type) {
                if (commonNewAdCallBack != null) {
                    commonNewAdCallBack.onLoadSuccess(adInfo);
                } else {
                    onLoadSuccess(adInfo);
                }

                if (!reportShow) {
                    reportShow = true;
                    ReportAgent.reportAdvExtShow(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                }
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
                LogUtils.e("CSJ onRenderFail ");
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
                //在渲染成功回调时展示广告，提升体验
                LogUtils.e("CSJ onRenderSuccess ");
                viewGroup.setVisibility(View.VISIBLE);
                viewGroup.removeAllViews();
                viewGroup.addView(view);
            }
        });
        ad.setDownloadListener(new TTAppDownloadListener() {

            boolean reportDownload;
            boolean reportInstall;

            @Override
            public void onIdle() {

            }

            @Override
            public void onDownloadActive(long l, long l1, String s, String s1) {

            }

            @Override
            public void onDownloadPaused(long l, long l1, String s, String s1) {

            }

            @Override
            public void onDownloadFailed(long l, long l1, String s, String s1) {

            }

            @Override
            public void onDownloadFinished(long l, String s, String s1) {
                if (!reportDownload) {
                    reportDownload = true;
                    ReportAgent.reportAdvDownload(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                }
            }

            @Override
            public void onInstalled(String s, String s1) {
                if (!reportInstall) {
                    reportInstall = true;
                    ReportAgent.reportAdvInstall(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                }
            }
        });
    }

    public void onLoadSuccess(String adSourceCode) {
        if(bannerAdConfig == null) {
            return;
        }
        bannerAdConfig.saveLastShowLocalAdCode(adSourceCode);
    }

    private void loadGdtBannerAd(final String code) {
        try {
            viewGroup.removeAllViews();
            View mCustomView = LayoutInflater.from(activity).inflate(R.layout.app_ad_gdt, null, false);
            viewGroup.addView(mCustomView);
            Button adBtn = mCustomView.findViewById(R.id.btn_download);
            NativeUnifiedAD mAdManager = new NativeUnifiedAD(Utils.getApp(), GDTConfig.APP_ID, code, new NativeADUnifiedListener() {
                @Override
                public void onADLoaded(List<NativeUnifiedADData> list) {
                    NativeUnifiedADData nativeUnifiedADData = list.get(0);
                    List<View> clickableViews = new ArrayList<>();
                    clickableViews.add(adBtn);
                    nativeUnifiedADData.bindAdToView(activity, mCustomView.findViewById(R.id.native_ad_container), null, clickableViews);
                    if (commonAdCallBack != null) {
                        commonAdCallBack.onLoadSuccess(code);
                    } else {
                        onLoadSuccess(code);
                    }
                    bindGDTAdView(mCustomView, nativeUnifiedADData);
                    nativeUnifiedADData.setNativeAdEventListener(new NativeADEventListener() {
                        @Override
                        public void onADExposed() {
                            SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_GDT, code, SDKReportHelper.OP_TYPE_SHOW);
                        }

                        @Override
                        public void onADClicked() {
                            SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_GDT, code, SDKReportHelper.OP_TYPE_CLICK);
                        }

                        @Override
                        public void onADError(AdError adError) {
                            SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_GDT, code, SDKReportHelper.OP_TYPE_FAIL);
                            viewGroup.removeAllViews();
                            if (commonAdCallBack != null) {
                                commonAdCallBack.onLoadFail(code, adError.getErrorMsg());
                            } else {
                                onLoadFail(code, adError.getErrorMsg());
                            }
                        }

                        @Override
                        public void onADStatusChanged() {
                            updateAdAction(adBtn, nativeUnifiedADData);
                        }
                    });
                    updateAdAction(adBtn, nativeUnifiedADData);
                }

                @Override
                public void onNoAD(AdError adError) {
                    SDKReportHelper.reportSDKAdv(SDKReportHelper.SOURCE_GDT, code, SDKReportHelper.OP_TYPE_FAIL);
                    viewGroup.removeAllViews();
                    if (commonAdCallBack != null) {
                        commonAdCallBack.onLoadFail(code, adError.getErrorMsg());
                    } else {
                        onLoadFail(code, adError.getErrorMsg());
                    }
                }
            });
            mAdManager.loadData(1);
        } catch (Exception ignored) {

        }
    }

    private void bindGDTAdView(View mCustomView, NativeUnifiedADData mAdData) {
        try {
            if (activity == null || activity.isDestroyed() || activity.isFinishing()) {
                return;
            }
            if (viewGroup != null && viewGroup.getVisibility() != View.VISIBLE) {
                viewGroup.setVisibility(View.VISIBLE);
            }
            ImageView mImagePoster = mCustomView.findViewById(R.id.img_poster);
            LinearLayout mLlImgs = mCustomView.findViewById(R.id.ll_3img_ad_container);
            ImageView mIvImg1 = mCustomView.findViewById(R.id.img_1);
            ImageView mIvImg2 = mCustomView.findViewById(R.id.img_2);
            ImageView mIvImg3 = mCustomView.findViewById(R.id.img_3);
            ImageView mIvLogo = mCustomView.findViewById(R.id.img_logo);
            TextView mTvTitle = mCustomView.findViewById(R.id.tv_title);
            TextView mTvDes = mCustomView.findViewById(R.id.tv_desc);
            int patternType = mAdData.getAdPatternType();
            LogUtils.e("patternType         " + patternType);
            mImagePoster.setVisibility(View.GONE);
            mLlImgs.setVisibility(View.GONE);
            if (patternType == AdPatternType.NATIVE_2IMAGE_2TEXT) {
                mTvTitle.setText(mAdData.getTitle());
                mTvDes.setText(mAdData.getDesc());
                ImageLoader.getInstance().displayImage(activity, mAdData.getImgUrl(), mIvLogo);
                ImageLoader.getInstance().displayImage(activity, mAdData.getImgUrl(), mImagePoster);
            } else if (patternType == AdPatternType.NATIVE_3IMAGE) {
                mTvTitle.setText(mAdData.getTitle());
                mTvDes.setText(mAdData.getDesc());
                ImageLoader.getInstance().displayImage(activity, mAdData.getImgList().get(0), mIvLogo);
                ImageLoader.getInstance().displayImage(activity, mAdData.getImgList().get(0), mIvImg1);
                ImageLoader.getInstance().displayImage(activity, mAdData.getImgList().get(1), mIvImg2);
                ImageLoader.getInstance().displayImage(activity, mAdData.getImgList().get(2), mIvImg3);
            } else if (patternType == AdPatternType.NATIVE_1IMAGE_2TEXT) {
                mTvTitle.setText(mAdData.getTitle());
                mTvDes.setText(mAdData.getDesc());
                ImageLoader.getInstance().displayImage(activity, mAdData.getImgUrl(), mIvLogo);
            }
        } catch (Exception ignored) {

        }
    }

    private void loadGdtBannerAd(final AdInfo adInfo) {
        try {
            viewGroup.removeAllViews();
            View mCustomView = LayoutInflater.from(activity).inflate(R.layout.app_ad_gdt, null, false);
            NativeUnifiedAD mAdManager = new NativeUnifiedAD(Utils.getApp(), GDTConfig.APP_ID, adInfo.getCode(), new NativeADUnifiedListener() {
                @Override
                public void onADLoaded(List<NativeUnifiedADData> list) {
                    NativeUnifiedADData nativeUnifiedADData = list.get(0);
                    List<View> clickableViews = new ArrayList<>();
                    Button adBtn = mCustomView.findViewById(R.id.btn_download);
                    viewGroup.addView(mCustomView);
                    clickableViews.add(adBtn);
                    nativeUnifiedADData.bindAdToView(activity, mCustomView.findViewById(R.id.native_ad_container), null, clickableViews);
                    bindGDTAdView(mCustomView, nativeUnifiedADData);
                    if (commonNewAdCallBack != null) {
                        commonNewAdCallBack.onLoadSuccess(adInfo);
                    } else {
                        onLoadSuccess(adInfo);
                    }
                    nativeUnifiedADData.setNativeAdEventListener(new NativeADEventListener() {
                        @Override
                        public void onADExposed() {
                            //广点通 广告显示上报
                            ReportAgent.reportAdvExtShow(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                        }

                        @Override
                        public void onADClicked() {
                            ReportAgent.reportAdvClick(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                        }

                        @Override
                        public void onADError(AdError adError) {
                            ReportAgent.reportAdvSdkFailed(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                            if (commonNewAdCallBack != null) {
                                commonNewAdCallBack.onLoadFail(adInfo, adError.getErrorMsg());
                            } else {
                                onLoadFail(adInfo, adError.getErrorMsg());
                            }
                        }

                        @Override
                        public void onADStatusChanged() {
                            updateAdAction(adBtn, nativeUnifiedADData);
                        }
                    });
                    updateAdAction(adBtn, nativeUnifiedADData);
                }

                @Override
                public void onNoAD(AdError adError) {
                    ReportAgent.reportAdvSdkFailed(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                    if (commonNewAdCallBack != null) {
                        commonNewAdCallBack.onLoadFail(adInfo, adError.getErrorMsg());
                    } else {
                        onLoadFail(adInfo, adError.getErrorMsg());
                    }
                }
            });

            mAdManager.loadData(1);
        } catch (Exception e) {

        }
    }

    public void destroy() {
        if (mTTNativateExpressAd != null) {
            mTTNativateExpressAd.destroy();
        }
    }
}
